<template>
  <div>
    <div class="header">集体劳动争议调解大赛</div>

    <div class="mainContent">
      <el-card class="box-card" v-show="!isMessage">
        <div class="content">
          <div class="title">
            <div style="color: #1E90FF;">案例背景介绍</div>
          </div>
          <div class="item">
            <span class="font-color">案例概要：<span>{{ list.summary }}</span></span>
          </div>
          <div class="item">
            <span class="font-color">调解员任务：{{ list.task }}</span>
          </div>
          <div style="display: flex; justify-content: center; align-items: center;">
            <el-button style="margin: 25px 0px;" type="success" @click="handleMessage">进入调解</el-button>
          </div>
        </div>
      </el-card>

      <el-card class="box-card" v-show="isMessage">
        <el-button type="danger" size="mini" :disabled="isRecognizing" style="margin-bottom: 5px;"
          :loading="isRecognizing" @click="start">
          <i class="el-icon-microphone"></i> 开始录音
        </el-button>
        <el-button type="danger" size="mini" :disabled="!isRecognizing" @click="stop">
          <i class="el-icon-switch-button"></i> 发送录音
        </el-button>
        <textarea class="sendMessage" v-model="form.input"></textarea>
        <div class="isMessageButton">
          <el-button type="primary" size="mini" @click="sendMessage">发 送</el-button>
          <!-- <el-button @click="closeMessage">关 闭</el-button> -->
        </div>
      </el-card>

    </div>
  </div>
</template>

<script>
import { testData, sendAiMessage, getList } from '@/api/exam/mediation'

export default {
  data() {
    return {
      form: {
        input: '',
        sessionIdPro: '',
        sessionIdCon: ''
      },
      isMessage: false,
      rules: {
        aiMessage: [
          { required: true, message: '请输入会话内容', trigger: 'blur' },
          { min: 1, max: 9999, message: '1~9999之间', trigger: 'blur' }
        ],
      },
      list: {
        summary: '',
        task: ''
      },

      isRecognizing: false,                 // 是否正在识别
      recognition: null,                    // 语音识别实例
      transcript: '',                       // 存储识别内容
      speechContent: {
        paragraphs: []
      },
      currentParagraph: {
        sentences: []
      }   // 当前段落


    }
  },

  mounted() {
    this.test(),
      this.load(),
      this.initSpeechRecognition()
  },

  methods: {

    test() {
      testData().then((res) => {
        localStorage.setItem('sessionData', JSON.stringify(res.data))
      })
    },

    load() {
      let id = JSON.parse(localStorage.getItem('examId'))
      let data = {
        id: id
      }
      getList(data).then((res) => {
        this.list.summary = res.data.summary
        this.list.task = res.data.task
      })
    },

    handleMessage() {
      this.isMessage = true
    },

    sendMessage() {
      let sessionData = JSON.parse(localStorage.getItem('sessionData'))
      this.form.sessionIdPro = sessionData[0].sessionId
      this.form.sessionIdCon = sessionData[1].sessionId
      sendAiMessage(this.form).then(res => {
        console.log(res)
      })
    },

    closeMessage() {
      this.isMessage = false
    },



    initSpeechRecognition() {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SpeechRecognition) {
      alert("您的浏览器不支持语音识别。\n请使用最新版 Chrome 或 Edge。");
      console.error("浏览器不支持 SpeechRecognition API");
      return;
    }

    this.recognition = new SpeechRecognition();
    this.recognition.lang = 'zh-CN';
    this.recognition.interimResults = true;
    this.recognition.continuous = true;

    this.recognition.onstart = () => {
      console.log('语音识别启动');
      this.isRecognizing = true;
    };

    this.recognition.onerror = (event) => {
      console.error('识别错误:', event.error);
      alert(`识别错误: ${event.error}`);
      this.isRecognizing = false;
    };

    this.recognition.onend = () => {
      console.log('语音识别结束');
      this.isRecognizing = false;
    };

    this.recognition.onresult = (event) => {
      let interimTranscript = '';
      let finalTranscript = '';

      for (let i = event.resultIndex; i < event.results.length; i++) {
        const result = event.results[i];
        const transcript = result[0].transcript.trim();

        if (result.isFinal) {
          this.currentParagraph.sentences.push({ finalTranscript: transcript });
          this.speechContent.paragraphs.push({ ...this.currentParagraph });
          this.currentParagraph = { sentences: [] };
          finalTranscript += transcript + ' ';
        } else {
          if (this.currentParagraph.sentences.length === 0) {
            this.currentParagraph.sentences.push({ interimTranscript: transcript });
          } else {
            this.currentParagraph.sentences[this.currentParagraph.sentences.length - 1].interimTranscript = transcript;
          }
          interimTranscript += transcript + ' ';
        }
      }

      this.transcript = finalTranscript + interimTranscript;
    };
  },

  start() {
    if (this.recognition && !this.isRecognizing) {
      this.recognition.start()
        .catch(err => {
          console.error("启动识别失败:", err);
          alert("无法启动语音识别，请检查麦克风权限。");
        });
    }
  },

  stop() {
    if (this.recognition && this.isRecognizing) {
      this.recognition.stop();
      this.currentParagraph = { sentences: [] }; // 清空临时段落
    }
  }



  }


}
</script>

<style lang="scss" scoped>
$header-height: 8vh; // 标题高度
$box-card-height: 28vh; // 案例div高度

.header {
  height: $header-height;
  width: 100%;
  color: #ffffff;
  background-color: #00008B;
  text-align: center;
  line-height: $header-height;
}

.mainContent {
  height: 100vh;
  background-image: url(../../../assets/web/images/mediation.jpg);
  display: flex;
  justify-content: center;
  align-items: center;

  .box-card {
    width: 80%;
    height: $box-card-height;
    opacity: 0.95;

    .content {
      .font-color {
        color: #0033CC;
      }

      .title {
        display: flex;
        justify-content: center;
      }

      .item {
        margin-top: 25px;
      }
    }

    .isMessageButton {
      display: flex;
      justify-content: end;
      align-items: center;
      position: relative;
      bottom: 40px;
    }
  }
}

.sendMessage {
  height: 180px;
  width: 100%;
  max-height: 180px;
  outline: none;
  border: none;
  border-top: 1px solid gray;
  resize: none;
  /* 禁止用户调整大小 */
  overflow-y: auto;
  /* 当内容超出时显示垂直滚动条 */
  padding: 10px;
  /* 添加内边距 */
  box-sizing: border-box;
  /* 包括内边距和边框在内的总宽度和高度 */
}
</style>